package com.ch.forum.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class VerificationCodeUtils {

    /**
     * 显示验证码图片
     */
    public void showCheckCode(String checkCode, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 调用业务逻辑
//        String checkCode = getCheckCode();
        //将验证码字符放入session域对象中
        req.getSession().setAttribute("checkCode", checkCode);

        //图片宽
        int width = 80;
        //图片高
        int height = 30;
        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //获取一个画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色，用灰色做背景
        g.setColor(Color.GRAY);
        //向Image中填充灰色
        g.fillRect(0,0,width,height);

        Random r = new Random();

        //设置3条干扰线
        for (int i = 0; i < 3; i++) {
            g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
            g.drawLine(r.nextInt(80), r.nextInt(30), r.nextInt(80), r.nextInt(80));
        }

        //设置验证码字符串的颜色
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        //设置字符的大小
        g.setFont(new Font("黑体",Font.BOLD,24));
        //在图片中写入验证码字符串
        g.drawString(checkCode,15,20);
        //将Image对象以PNG格式输出给所有的客户端
        ImageIO.write(image,"PNG",resp.getOutputStream());
    }

    /**
     * 获取4位验证码中的4位随机字符串
     */
    public static String getCheckCode(){
        //验证码中的字符由数字和大小写字母组成
        String code = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            sb.append(code.charAt(r.nextInt(code.length())));
        }

        return sb.toString();
    }
}
